package com.bdqn.systems.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.enums.UserStatusEnum;
import com.bdqn.enums.UserTypeEnum;
import com.bdqn.exception.BusinessException;
import com.bdqn.response.ResultCode;
import com.bdqn.systems.entity.User;
import com.bdqn.systems.mapper.UserMapper;
import com.bdqn.systems.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.systems.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author cp
 * @since 2020-11-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Page<User> getUserList(Page<User> page, UserVo userVo) {
        List<User> userList = this.baseMapper.getUserList(page, userVo);
        return page.setRecords(userList);
    }

    @Override
    public List<User> findUserList(UserVo userVo) {
        return this.baseMapper.getUserList(null, userVo);
    }

    @Override
    public Integer del(Long id) {
        int i = this.baseMapper.deleteById(id);
        if(i<=0){
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        return i;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public Integer insert(User user) {
        // 用户是否重复
        this.getNotNullName(user.getUsername());
        // 状态绑定
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        // 用户权限
        user.setType(UserTypeEnum.SYSTEM_ADMIN.getTypeCode());
        // 盐
        String salt = UUID.randomUUID().toString().substring(0,32);
        user.setSalt(salt);
        // 密码加密
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);

        return this.baseMapper.insert(user);
    }

    /**
     * 判断用户名是否存在
     * @param username
     * @return
     */
    @Override
    public Integer getNotNullName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Integer integer = this.baseMapper.selectCount(wrapper);
        if(integer>0){
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        return integer;
    }

    @Override
    public boolean editUserState(Integer id) {
        User user = this.baseMapper.selectById(id);
        Integer i = user.getStatus().equals(UserStatusEnum.DISABLE.getStatusCode())
                ?UserStatusEnum.AVAILABLE.getStatusCode()
                :UserStatusEnum.DISABLE.getStatusCode();
        user.setStatus(i);
        return this.updateById(user);
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> users) throws IOException {

        //----- 写入excel文件
        String exportFileName = "用户列表.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }

    @Override
    public User selectByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return this.baseMapper.selectOne(wrapper);
    }

}
